package com.study.testEasyExcel.handler;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.study.testEasyExcel.test.DemoData;
import com.study.testEasyExcel.test.UploadDataListener;

@Controller
public class OperateHandler {
	
	@GetMapping("/index")
	public String index() {
		return "index";
	}
	
	@GetMapping("/success")
	public String success() {
		return "success";
	}

	@GetMapping("/downLoad")
	public void downLoadExcel(HttpServletResponse resp) throws Exception {
		// 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
		resp.setContentType("application/vnd.ms-excel");
		resp.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8");
        resp.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(resp.getOutputStream(), DemoData.class).sheet("模板").doWrite(data());
	}
	
	/**
     * 文件上传
     * <p>1. 创建excel对应的实体对象 参照{@link UploadData}
     * <p>2. 由于默认异步读取excel，所以需要创建excel一行一行的回调监听器，参照{@link UploadDataListener}
     * <p>3. 直接读即可
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), DemoData.class, new UploadDataListener()).sheet().doRead();
        return "success";
    }
	
	public static List<DemoData> data() {
    	List<DemoData> list = new ArrayList<>();
    	list.add(new DemoData("aaa","aaa","1.1.1.1"));
    	list.add(new DemoData("bbb","bbb","1.1.1.2"));
    	list.add(new DemoData("ccc","ccc","1.1.1.3"));
    	
    	return list;
    }
}
